<?php
/**
 * Portlet class file
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: Portlet.php 472 2011-01-25 17:27:19Z steen.rabol $
 * @package Pradoportal.Portlets
 */

/**
 * Portlet class
 *
 * This is the base class for all portlets.
 * @package Pradoportal.Portlets
 *
 */

Prado::using('Application.Common.Data.PortalPagecontentRecord');
Prado::using('Application.Common.Data.PortalConfigRecord');

abstract class Portlet extends TTemplateControl
{
	private $_parameters;
	private	$_hasAdminFunc			= false;
	private	$_hasPropertyFunction	= true;
	private	$_hasDeleteFunction		= true;

	private $_templateName;
	private	$_langstrings			= array();
	private	$_langkey				= "";

	/*
	 * Configuration record
	 */
	private $_configrecord			= null;
	private $_properties			= null;

	/*
	 * Data record for the portlet
	 */
	private $_portletrecord			= null;


	public function __construct($parm = null)
	{
		$this->Parameters = $parm;

		// Set the language key to APPLICATION, in order to default to application wide strings
		$this->LanguageKey	= 'APPLICATION';
	}

	public function onInit($p)
	{
		parent::onInit($p);
       
		if($this->LanguageKey !== 'APPLICATION')
		{
			$this->Application->loadLanguageStrings($this->LanguageKey);
		}

		// Load the config record
		if(!is_null($this->ConfigName))
		{
			$this->ConfigRecord = PortalConfigRecord::finder()->findByname($this->ConfigName);
			if(!$this->ConfigRecord)
			{
				$this->ConfigRecord = new PortalConfigRecord();
				$this->ConfigRecord->name = $this->ConfigName;
				$this->ConfigRecord->save();
			}
		}

		if(!is_null($this->PropertyName))
		{
			$p = PortalConfigRecord::finder()->findByname($this->PropertyName);
			if(!is_null($p))
			{
				$this->CustomProperties = Prado::unserialize($p->value);
			}
		}
	}

	protected function getConfigName()
	{
		return null;
	}

	protected function getPropertyName()
	{
		return null;
	}

	public function getPortletRecord()
	{
		return $this->_portletrecord;
	}

	public function setPortletRecord($p)
	{
		$this->_portletrecord = $p;
	}

	public function getConfigRecord()
	{
		return $this->_configrecord;
	}

	public function setConfigRecord($value)
	{
		$this->_configrecord	= $value;
	}

	public function setLanguageKey($key)
	{
		$this->_langkey	= $key;
	}

	public function getLanguageKey()
	{
		return $this->_langkey;
	}

	protected function loadTemplate()
	{
		$tplName	= get_class($this) . '.tpl';
        $tplDir		= $this->Application->PortalBasePath . '/themes/Portal/' . $this->Application->Parameters['ThemeName'] . '/Portlets/' .get_class($this);

		if(!file_exists($tplDir . '/' . $tplName))
		{
			return parent::loadTemplate();
		}

		if($this->Page->EditMode == 1)
		{
			$tplFile	= $tplDir . '/Edit/' . $tplName;
		}
		else
		{
			$tplFile	= $tplDir . '/' . $tplName;
		}
        
		if(file_exists($tplDir) && file_exists($tplFile))
		{
			$this->setTemplateName($tplFile);
		}
		else
		{
			if($this->Page->EditMode == 1)
			{
				$this->setTemplateName($this->Application->PortalBasePath . '/protected/Portlets/' . get_class($this) .  '/Edit/' .$tplName);
			}
			else
			{
				$this->setTemplateName($this->Application->PortalBasePath . '/protected/Portlets/' . get_class($this) .  '/' .$tplName);
			}
		}

		$template = $this->getService()->getTemplateManager()->getTemplateByFileName($this->_templateName);
		return $template;
	}

	public function setTemplateName($fileName)
	{
		$this->_templateName = $fileName;
	}

	public function getTemplateName()
	{
		return $this->_templateName;
	}

	public function getPageName()
	{
		return $this->Service->RequestedPagePath;
	}

	public function getVersion()
	{
		// Core portlets have the same version number as the Portal
		// Custom portlets should override this method.
		$this->Application->PortalVersion();
	}

	//
	// Properties
	//

	public function setHasAdminFunc($value)
	{
		$this->_hasAdminFunc	= $value;
	}

	public function getHasAdminFunc()
	{
		return $this->_hasAdminFunc;
	}

	public function getParameters()
	{
		return $this->_parameters;
	}

	public function setParameters($p)
	{
		$this->_parameters = $p;
	}

	public function getPropertyFunction()
	{
		return $this->_hasPropertyFunction;
	}

	public function setPropertyFunction($value)
	{
		$this->_hasPropertyFunction = $value;
	}

	public function getDeleteFunction()
	{
		return $this->_hasDeleteFunction;
	}

	public function setDeleteFunction($value)
	{
		$this->_hasDeleteFunction = $value;
	}

	public function getDataAccess()
	{
		return $this->Application->DbConnection;
	}

	public function render($writer)
	{
		$am			= $this->Application->getModule('auth');
		$canedit	= $am->CanEdit();

		if($this->Page->EditMode == 1 && $canedit)
		{
			$id = "adm_" . uniqid();
			$writer->write("<div id='$id' style='border: 1px dotted green; margin: 3px;'>");
			parent::render($writer);
			$writer->write("</div>");
		}
		else
		{
			parent::render($writer);
		}
	}

	public function UpButtonClicked($sender,$param)
	{
		$id		= $this->Parameters['id'];
		$row	= $this->DataAccess->createCommand("select * from tblpagecontent where id=$id")->queryRow();

		if($row !== false)
		{
			$this->DataAccess->createCommand("update tblpagecontent set displayorder=displayorder -1.001 where id=$id")->execute();
			$this->RenumDisplayOrder();
			$this->RenumDisplayOrder(1);
		}
		$this->Page->gotoPage($this->Parameters['pagename'],array("PageMode" => $this->Page->EditMode));
	}

	public function DownButtonClicked($sender,$param)
	{
		$id		= $this->Parameters['id'];
		$row	= $this->DataAccess->createCommand("select * from tblpagecontent where id=$id")->queryRow();

		if($row !== null)
		{
			$this->DataAccess->createCommand("update tblpagecontent set displayorder=displayorder +1.001 where id=$id")->execute();
			$this->RenumDisplayOrder();
			$this->RenumDisplayOrder(1);
		}

		$this->Page->gotoPage($this->Parameters['pagename'],array("PageMode" => $this->Page->EditMode));
	}

	public function PropertyButtonClicked($sender,$param)
	{
		$this->Page->gotoPage('System.PropertyPortlet',array('PageMode' => $this->Page->EditMode,'pid' => $this->Parameters['pagename'],'cid' => $this->Parameters['controlname'],"poid" => $this->Parameters['id'],"pname" => $this->Parameters['portlet']));
	}

 	public function MoveButtonClicked($sender,$param)
	{
		$appla	= $this->Application->LayoutAreas;
		$l		= array();

		for($i = 0; $i < count($appla); $i++)
		{
			$l[] = $appla[$i]['id'];
		}

		$la = implode(";",$l);
		$this->Page->gotoPage('System.MovePortlet',array('la' => $la, 'PageMode' => $this->Page->EditMode,'pid' => $this->Parameters['pagename'],'cid' => $this->Parameters['controlname'],"poid" => $this->Parameters['id'],"pname" => $this->Parameters['portlet']));
	}

	public function DeleteButtonClicked($sender,$param)
	{
		$finder	= PortalPagecontentRecord::finder();
		$finder->deleteByPk($this->Parameters['id']);
		$this->Page->gotoPage($this->Parameters['pagename'],array("PageMode" => $this->Page->EditMode));
	}

	public function RenumDisplayOrder($p_startat = 999.000)
	{
		$newdisplayorder = $p_startat;
		$pid	= $this->Parameters['pagename'];
		$cid	= $this->Parameters['controlname'];
		$sql	= "select * from tblpagecontent where pagename='$pid' && controlname='$cid' order by displayorder";
		$rows	= $this->DataAccess->createCommand($sql)->query();

		if($rows)
		{
			foreach($rows as $row)
			{
				$sql = "update tblpagecontent set displayorder=$newdisplayorder where id='" . $row["id"] . "'";
				$this->DataAccess->createCommand($sql)->execute();
				$newdisplayorder++;
			}
		}
	}

	// Installation

	public function PortletInstall()
	{
		$installfile	= $this->Application->BasePath . "/Portlets/" . get_class($this) . "/Install/" . $this->Application->Parameters['DbType'] . ".php";

		if(file_exists($installfile))
		{
			require_once($installfile);

			// Read the file and execute the SQL
			if(is_array($drop_table))
			{
				// First we drop the tables
				foreach($drop_table as $dtsql)
				{
					$this->DataAccess->createCommand(trim($dtsql))->execute();
				}
			}

			if(is_array($create_table))
			{
				// let's create the tables
				foreach($create_table as $ctsql)
				{
					$this->DataAccess->createCommand(trim($ctsql))->execute();
				}
			}
		}

		// Copy Admin files
		$padmDir	= $this->Application->BasePath . "/Portlets/" . get_class($this) . "/Admin/Pages";
		$admFiles	= PortalUtil::getFilesInPath($padmDir);
		if($admFiles)
		{
			$destDir	= Prado::getPathOfNamespace('Application.Pages.Admin.Portlets.' . get_class($this));
			PortalUtil::CreateDirStructure($destDir);
			
			foreach ($admFiles as $admFile)
			{
				try 
				{
					copy($padmDir . '/' . $admFile, $destDir . '/' . $admFile);
					try
					{
						chmod($destDir . '/' . $admFile,0777);
					}
					catch(Exception $e)
					{
						$service		= $this->Application->Service;
						$this->Response->redirect($service->constructUrl('System.ErrorReport',array('id'=>0,'msg' => urldecode($this->getApplication()->getSecurityManager()->hashData(Prado::localize('Faild to set permission on file file {0} : {1}', array($destDir . '/' .$admFile,$e->getMessage())))))));
					}
				}
				catch (Exception $e)
				{
					$application	= Prado::getApplication();
					$service		= $application->Service;

					$this->Response->redirect($service->constructUrl('System.ErrorReport',array('id'=>0,'msg' => urldecode($this->getApplication()->getSecurityManager()->hashData(Prado::localize('Faild to copy file {0} to {1}', array($admFile,$destDir)))))));
				}
			}
		}

		return true;
	}

	function PortletUnInstall()
	{
		// Read the installation file
		$installfile	= $this->Application->BasePath . "/Portlets/" . get_class($this) . "/Install/" . $this->Application->Parameters['DbType'] . ".php";

		if(file_exists($installfile))
		{
			require_once($installfile);
			if(is_array($drop_table))
			{
				foreach($drop_table as $dtsql)
				{
					$this->DataAccess->createCommand(trim($dtsql))->execute();
				}
			}
		}
		return true;
	}

	public function SearchQuery($queryvalue)
	{
		return null;
	}

	public function getCustomProperties()
	{
		return $this->_properties;
	}

	public function setCustomProperties($value)
	{
		$this->_properties	= $value;
	}
	
	public function getBaseUrl()
	{
		return $this->Page->getTheme()->getBaseUrl();
	}

	public static function getAdminMenus()
	{
		return null;
	}
}
?>